/*
 * Copyright 2008 Wink Saville
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.saville.serdes;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.io.UnsupportedEncodingException;
import com.saville.debug.Log;

/*
 * Serialize primitive types to a byte array.
 * 
 * TODO: Add read/write float/double
 * TODO: What about read/write char?
 * TODO: What about arrays of char/short/int/float/doubles?
 * TODO: This serializes in low byte first (little endian), but I notice that
 * DataOutputStream/DataInputStream uses high byte first (big endian). Should
 * I change this to high byte first?
 */
public class SerdesBinary {

    public SerdesBinary() {
        data = new byte[32];
        offset = 0;
    }

    public SerdesBinary(int len) {
        data = new byte[len];
        offset = 0;
    }

    public SerdesBinary(byte data[], int offset) {
        this.data = data;
        this.offset = offset;
    }

    public int size() {
        return offset;
    }

    public byte[] data() {
        return this.data;
    }

    public SerdesBinary init() {
        this.offset = 0;
        return this;
    }

    public SerdesBinary init(byte data[], int offset, int len) {
        this.data = data;
        this.offset = offset;
        return this;
    }

    public void writeBoolean(boolean v) {
        check(1);
        data[offset + 0] = (byte) (v ? 1 : 0);
        offset += 1;
    }

    public void writeByte(int v) {
        check(1);
        data[offset + 0] = (byte) (v & 0xff);
        offset += 1;
    }

    public void writeShort(int v) {
        check(2);
        data[offset + 0] = (byte) (v & 0xff);
        data[offset + 1] = (byte) ((v >> 8) & 0xff);
        offset += 2;
    }

    public void writeInt(int v) {
        check(4);
        data[offset + 0] = (byte) (v & 0xff);
        data[offset + 1] = (byte) ((v >> 8) & 0xff);
        data[offset + 2] = (byte) ((v >> 16) & 0xff);
        data[offset + 3] = (byte) ((v >> 24) & 0xff);
        offset += 4;
    }

    public void writeLong(long v) {
        check(8);
        data[offset + 0] = (byte) (v & 0xff);
        data[offset + 1] = (byte) ((v >> 8) & 0xff);
        data[offset + 2] = (byte) ((v >> 16) & 0xff);
        data[offset + 3] = (byte) ((v >> 24) & 0xff);
        data[offset + 4] = (byte) ((v >> 32) & 0xff);
        data[offset + 5] = (byte) ((v >> 40) & 0xff);
        data[offset + 6] = (byte) ((v >> 48) & 0xff);
        data[offset + 7] = (byte) ((v >> 56) & 0xff);
        offset += 8;
    }

    public void writeBytes(byte b[]) {
        check(b.length + 4);
        writeInt(b.length);
        System.arraycopy(b, 0, data, offset, b.length);
        offset += b.length;
    }

    public void writeString(String str) {
        try {
            if (str != null) {
                writeBytes(str.getBytes("UTF-8"));
            } else {
                writeInt(0); // Length is 0
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Serdes#writeString: Bug; UTF-8 encoding not supported");
        }
    }

    public boolean readBoolean() {
        boolean v;
        v = data[offset + 0] == 1;
        offset += 1;
        return v;
    }

    public byte readByte() {
        byte v;
        v = data[offset + 0];
        offset += 1;
        return v;
    }

    public int readUnsignedByte() {
        return readByte() & 0xff;
    }

    public short readShort() {
        int v;
        v = data[offset + 0] & 0xff;
        v = v | ((data[offset + 1] & 0xff) << 8);
        offset += 2;
        return (short) v;
    }

    public int readUnsignedShort() {
        return readShort() & 0xffff;
    }

    public int readInt() {
        int v;
        v = data[offset + 0] & 0xff;
        v = v | ((data[offset + 1] & 0xff) << 8);
        v = v | ((data[offset + 2] & 0xff) << 16);
        v = v | ((data[offset + 3] & 0xff) << 24);
        offset += 4;
        return v;
    }

    public long readLong() {
        long v;
        v = data[offset + 0] & 0xff;
        v = v | ((long) (data[offset + 1] & 0xff) << 8);
        v = v | ((long) (data[offset + 2] & 0xff) << 16);
        v = v | ((long) (data[offset + 3] & 0xff) << 24);
        v = v | ((long) (data[offset + 4] & 0xff) << 32);
        v = v | ((long) (data[offset + 5] & 0xff) << 40);
        v = v | ((long) (data[offset + 6] & 0xff) << 48);
        v = v | ((long) (data[offset + 7] & 0xff) << 56);
        offset += 8;
        return v;
    }

    public byte[] readBytes() {
        int len = readInt();
        byte b[] = new byte[len];
        System.arraycopy(data, offset, b, 0, len);
        offset += len;
        return b;
    }

    public String readString() {
        byte b[] = readBytes();
        if (b.length == 0)
            return null;
        else
            return new String(b);
    }

    public void writeObject(Object obj) {
        if (obj == null) {
            writeInt(0); // type 0 is null object
        } else {
            try {
                // TODO: "Type safety warning"
                ((ISerdes) obj).serialize(this);
            } catch (Exception e) {
                // TODO: What should this really do?
                Log.print("Serdes: writeObject Bug");
                Log.printStackTrace(e);
                throw new RuntimeException("Serdes#writeObject Exception");
            }
        }
    }

    public Object readObject() {
        Object o;
        int id;

        id = readInt();
        if (id == 0) {
            // id 0 is a null
            o = null;
        } else {
            ISerdes s = mapping.get(id);
            if (s == null) {
                /* TODO: Load the class here? */
                throw new RuntimeException("Serdes: id=" + id + " not present");
            }
            s = (ISerdes) s.make();
            o = s.deserialize(this);
        }

        return o;
    }

    /*
     * register an object that implements ISerdes
     * 
     * @throws RuntimeException if a mapping already exists (this is bug)
     */
    public static void register(int id, ISerdes s) {
        Object o = mapping.put(id, s);
        if (o != null) {
            throw new RuntimeException("Serdes: Mapping for " + id + " already exists for " + o);
        }
    }

    private void check(int len) {
        if ((offset + len) >= data.length) {
            byte d[] = new byte[data.length + (len * 8)];
            System.arraycopy(data, 0, d, 0, data.length);
            data = d;
        }
    }

    private int offset;
    private byte data[];

    private static Map<Integer, ISerdes> mapping = Collections
            .synchronizedMap(new HashMap<Integer, ISerdes>());
}
